import json
from dingtalkchatbot.chatbot import DingtalkChatbot
import zmail
import requests
import time


from utils.get_test_result_data import get_test_result_data
from utils.config_parser import GetConfig

class SendMessage:
    def __init__(self, env):

        report_link_dict = {
            "test": "report_link_test",
            "sting": "report_link_sting",
            "prod": "report_link_prod"
        }
        report_link = report_link_dict.get(env, "report_link_prod")

        #self.report_link = report_link_new
        self.get_config = GetConfig()
        self.report_link = self.get_config.get_message_report_path().get(report_link)
        self.now = time.strftime("%Y-%m-%d %H:%M:%S")
        # 获取钉钉消息配置
        self.config_dingding = self.get_config.get_message_dingding()

        # 获取企业微信消息配置
        self.config_wechat = self.get_config.get_message_wechat()

        # 获取邮箱配置
        self.config_email = self.get_config.get_message_email()

        # 从allure的json报告中获取测试结果
        self.result = get_test_result_data()
        self.passed = self.result.get("passed", 0)
        self.failed = self.result.get("failed", 0)
        self.skipped = self.result.get("skipped", 0)

        def send_message(self):
            raise NotImplementedError("发送消息的子类必须实现的方法")

class SendDingDingMessage(SendMessage):
    def send_message(self):
        # 接口测试报告
        # 1.名字：接口自动化测试报告
        # 2.测试时间是什么时间
        # 3.测试结果概述
        # 4.测试报告连接

        # ding = DingtalkChatbot(webhook, secret)
        ding = DingtalkChatbot(self.config_dingding.get("webhook"), self.config_dingding.get("secret"))
        ding.send_markdown("接口自动化测试报告", text=f"""
**接口自动化测试概述**
- **测试时间**: {self.now}
- **测试结果**:
- 成功: {self.passed}条

- 失败: {self.failed}条


- 跳过: {self.skipped}条
- **测试报告链接**: [点击访问]({self.report_link})
""")


class SendMailMessage(SendMessage):
    def send_message(self):
        # mail = zmail.server(mail_username, mail_password)
        mail = zmail.server(self.config_email.get('mail_username'), self.config_email.get('mail_password'))
        mail.send_mail(
            recipients=self.config_email.get('recipients'),
            mail={
                "subject":"接口自动化通知","content_html":'''
                <!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>接口自动化测试报告</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }

        .title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .info-item {
            margin-bottom: 5px;
        }

        .link {
            color: #0066cc;
            text-decoration: none;
        }

        .link:hover {
            text-decoration: underline;
        }
    </style>
</head>

<body>
    <div class="title">**接口自动化测试概述**</div>
    <div class="info-item">**测试时间**：{self.now}</div>
    <div class="info-item">**测试结果**：</div>
    <div class="info-item">成功：{self.passed}条</div>
    <div class="info-item">失败：{self.failed}条</div>
    <div class="info-item">跳过：{self.skipped}条</div>
    <div class="info-item">**测试报告链接**：<a href="{self.report_link}" class="link">[点击访问]</a></div>
</body>

</html>'''
            })


class SendChatMessage(SendMessage):
    def send_message(self):
        data = {
            "msgtype": "markdown",
            "markdown": {
                "content": """
**接口自动化测试概述**  
**测试时间**：{self.now}  
**测试结果**：  
成功：{self.passed}条  
失败：{self.failed}条  
跳过：{self.skipped}条  
**测试报告链接**：[点击访问]({self.report_link})  
"""
            }
        }
        requests.post(
            url=self.config_wechat.get('webhook'),
            headers=self.config_wechat.get('headers'),
            data=json.dumps(data)
        )

def send_message(env):
    """
    消息通知实际调用的函数
    :return:
    """
    message_object = [
        SendDingDingMessage(env),
        # SendChatMessage(env),
        SendMailMessage(env)
    ]

    for mo in message_object:
        mo.send_message()


if __name__ == '__main__':
    send_message("test")